// lib/pages/comic_reader_page.dart
import 'dart:async';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../models/comic_chapter_model.dart';
import '../home/model/comic_detail_model.dart';
import 'new_reader_providers.dart';

class ComicReaderPage extends ConsumerStatefulWidget {
  final ComicDetailModel detail;
  final String? initialChapterId; // 可选：如果不传则取 detail.comicChapters.first

  const ComicReaderPage(
      {super.key, required this.detail, required this.initialChapterId});

  @override
  ConsumerState<ComicReaderPage> createState() => _ComicReaderPageState();
}

class _ComicReaderPageState extends ConsumerState<ComicReaderPage>
    with TickerProviderStateMixin {
  PageController? _pageController;
  ScrollController? _scrollController;
  bool _isControllerInitialized = false;
  Timer? _hideToolbarTimer;

  @override
  void initState() {
    super.initState();
    // 在 frame 回调里设置 providers（确保 context 已可用）
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      // 存储整个 ComicDetailModel（用于目录等）
      ref.read(comicDetailProvider.notifier).state = widget.detail;

      // 选择初始 chapter id：优先传入 initialChapterId，否则使用 detail 中第一章
      String? startId = widget.initialChapterId;
      if (startId == null) {
        final chapters = widget.detail.comicChapters;
        if (chapters != null && chapters.isNotEmpty) {
          startId = chapters.first.chapterId;
        }
      }
      if (startId != null) {
        ref.read(currentChapterIdProvider.notifier).state = startId;
      }

      // 可选：加载并跳转到上次阅读位置（基于 comicId）
      final comicId = widget.detail.comic?.id ?? widget.detail.comic?.id ?? '';
      if (comicId.isNotEmpty) {
        final lastIndex =
            await ref.read(readingPersistenceProvider).loadLastIndex(comicId);
        ref.read(lastReadIndexProvider(comicId).notifier).state = lastIndex;
        // 如果你想自动跳到该页（只在 horizontal 模式或已知高度时有效）
        // ref.read(currentIndexProvider.notifier).state = lastIndex;
      }
    });
  }

  @override
  void dispose() {
    _pageController?.dispose();
    _scrollController?.dispose();
    _hideToolbarTimer?.cancel();
    super.dispose();
  }

  void _autoHideToolbar() {
    _hideToolbarTimer?.cancel();
    _hideToolbarTimer = Timer(const Duration(seconds: 4), () {
      ref.read(toolbarVisibleProvider.notifier).state = false;
    });
  }

  void _onTapCenter() {
    final visible = ref.read(toolbarVisibleProvider);
    ref.read(toolbarVisibleProvider.notifier).state = !visible;
    if (!visible) _autoHideToolbar();
  }

  Future<void> _precacheNextImage(List<String> urls, int index) async {
    final nextIndex = index + 1;
    if (nextIndex < urls.length) {
      final url = urls[nextIndex];
      try {
        await precacheImage(ExtendedNetworkImageProvider(url), context);
      } catch (_) {}
    }
  }

  Future<void> _maybeLoadNextChapterIfNeeded(ComicChaptersModel current) async {
    print("加载下一章节");

    final repo = ref.read(chapterRepoProvider);
    final nextFromApi = await repo.fetchNextChapter(current);

    String? nextId;

    if (nextFromApi != null && nextFromApi.id != null) {
      nextId = nextFromApi.id!;
    } else {
      final currentId = current.chapterId ?? '';
      nextId = nextChapterIdFromList(ref, currentId);
    }

    if (nextId != null) {
      // 更新章节ID
      ref.read(currentChapterIdProvider.notifier).state = nextId;
      // 重置索引
      ref.read(currentIndexProvider.notifier).state = 0;

      // 🟢 ListView 模式：滚动到顶部
      if (_scrollController != null) {
        _scrollController!.jumpTo(0);
      }

      return;
    }

    ScaffoldMessenger.of(context)
        .showSnackBar(const SnackBar(content: Text('已经是最后一章')));
  }

  void _initControllersIfNeeded(int initialPage, bool isVertical) {
    if (_isControllerInitialized) return;
    if (isVertical) {
      _scrollController = ScrollController(initialScrollOffset: 0.0);
    } else {
      _pageController = PageController(initialPage: initialPage);
    }
    _isControllerInitialized = true;
  }

  @override
  Widget build(BuildContext context) {
    final curChapterId = ref.watch(currentChapterIdProvider);
    if (curChapterId == null) {
      return const Scaffold(
        body: Center(child: Text('没有章节id')),
      );
    }

    final chapterAsync = ref.watch(chapterProvider(curChapterId));
    final isVertical = ref.watch(isVerticalScrollProvider);
    final toolbarVisible = ref.watch(toolbarVisibleProvider);
    final nightMode = ref.watch(nightModeProvider);

    return chapterAsync.when(
      loading: () => const Center(
        child: CircularProgressIndicator(color: Color(0xFF6C5CE7)),
      ),
      error: (e, st) => Scaffold(body: Center(child: Text('加载章节失败: $e'))),
      data: (chapter) {
        if (chapter == null) {
          return Scaffold(body: Center(child: Text('章节无内容')));
        }
        final images = chapter.imageUrls;

        final initialIndex = ref.read(currentIndexProvider);
        _initControllersIfNeeded(initialIndex, isVertical);

        final bgColor = nightMode ? Colors.black : Colors.white;

        return Scaffold(
          extendBodyBehindAppBar: true,
          body: Stack(
            children: [
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: _onTapCenter,
                child: isVertical
                    ? MediaQuery.removePadding(
                        context: context,
                        removeTop: true,
                        removeBottom: true,
                        child: ListView.builder(
                          controller: _scrollController,
                          itemCount: images.length,
                          itemBuilder: (context, index) {
                            final url = images[index];
                            // 预加载下一张
                            if (index == ref.read(currentIndexProvider)) {
                              _precacheNextImage(images, index);
                            }

// 检查是否到达最后一页
                            if (index == images.length - 1) {
                              // 获取当前章节ID
                              final currentChapterId =
                                  ref.read(currentChapterIdProvider);

                              // 在章节列表中找到当前章节的索引
                              final chapters =
                                  widget.detail.comicChapters ?? [];
                              final currentChapterIndex = chapters.indexWhere(
                                  (chapter) =>
                                      chapter.chapterId == currentChapterId);

                              // 检查是否有下一章节
                              if (currentChapterIndex >= 0 &&
                                  currentChapterIndex < chapters.length - 1) {
                                final nextChapter =
                                    chapters[currentChapterIndex + 1];
                                _maybeLoadNextChapterIfNeeded(nextChapter);
                              }
                            }

                            return Container(
                              color: bgColor,
                              // padding: const EdgeInsets.symmetric(vertical: 8),
                              // alignment: Alignment.center,
                              child: ExtendedImage.network(
                                url,
                                cache: true,
                                fit: BoxFit.contain,
                                mode: ExtendedImageMode.gesture,
                                initGestureConfigHandler: (state) {
                                  return GestureConfig(
                                    minScale: 1.0,
                                    maxScale: 3.0,
                                    animationMinScale: 0.7,
                                    animationMaxScale: 3.5,
                                    speed: 1.0,
                                    inertialSpeed: 100.0,
                                    initialScale: 1.0,
                                    inPageView: !isVertical,
                                  );
                                },
                                loadStateChanged: (state) {
                                  switch (state.extendedImageLoadState) {
                                    case LoadState.loading:
                                      return const SizedBox(
                                          height: 300,
                                          child: Center(
                                              child:
                                                  CircularProgressIndicator()));
                                    case LoadState.completed:
                                      return ExtendedRawImage(
                                        image: state.extendedImageInfo?.image,
                                        fit: BoxFit.contain,
                                      );
                                    case LoadState.failed:
                                      return const SizedBox(
                                          height: 300,
                                          child: Center(
                                              child: Icon(Icons.broken_image)));
                                  }
                                },
                              ),
                            );
                          },
                        ),
                      )
                    : PageView.builder(
                        controller: _pageController,
                        itemCount: images.length,
                        onPageChanged: (index) {
                          ref.read(currentIndexProvider.notifier).state = index;
                          _precacheNextImage(images, index);
                          // if (index == images.length - 1) {
                          //   // 到达最后一页，尝试加载下一章
                          //   _maybeLoadNextChapterIfNeeded(chapter, index);
                          // }
                        },
                        itemBuilder: (context, index) {
                          final url = images[index];
                          // 为 PageView 中的 ExtendedImage 提供手势
                          return Center(
                            child: ExtendedImage.network(
                              url,
                              cache: true,
                              fit: BoxFit.contain,
                              mode: ExtendedImageMode.gesture,
                              initGestureConfigHandler: (state) {
                                return GestureConfig(
                                  minScale: 1.0,
                                  maxScale: 3.0,
                                  animationMinScale: 0.7,
                                  animationMaxScale: 3.5,
                                  speed: 1.0,
                                  inertialSpeed: 100.0,
                                  initialScale: 1.0,
                                  inPageView: true,
                                );
                              },
                              loadStateChanged: (state) {
                                switch (state.extendedImageLoadState) {
                                  case LoadState.loading:
                                    return SizedBox(
                                        height: 300,
                                        child: Center(
                                            child:
                                                CircularProgressIndicator()));
                                  case LoadState.completed:
                                    return ExtendedRawImage(
                                      image: state.extendedImageInfo?.image,
                                      fit: BoxFit.contain,
                                    );
                                  case LoadState.failed:
                                    return SizedBox(
                                        height: 300,
                                        child: Center(
                                            child: Icon(Icons.broken_image)));
                                }
                              },
                            ),
                          );
                        },
                      ),
              ),

              // Top toolbar
              AnimatedPositioned(
                duration: const Duration(milliseconds: 200),
                top: toolbarVisible ? 0 : -80,
                left: 0,
                right: 0,
                child: AnimatedOpacity(
                  opacity: toolbarVisible ? 1 : 0,
                  duration: const Duration(milliseconds: 200),
                  child: _buildTopToolbar(chapter),
                ),
              ),

              // Bottom toolbar
              AnimatedPositioned(
                duration: const Duration(milliseconds: 200),
                bottom: toolbarVisible ? 0 : -100,
                left: 0,
                right: 0,
                child: AnimatedOpacity(
                  opacity: toolbarVisible ? 1 : 0,
                  duration: const Duration(milliseconds: 200),
                  child: _buildBottomToolbar(chapter, images.length),
                ),
              ),

              // optional: page index overlay
              Positioned(
                right: 10,
                bottom: 140,
                child: Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: Text(
                    '${ref.watch(currentIndexProvider) + 1}/${images.length}',
                    style: const TextStyle(color: Colors.white),
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }

  Widget _buildTopToolbar(ComicChapterModel chapter) {
    return Container(
      color: Colors.black.withOpacity(0.6),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      child: SafeArea(
        top: true,
        bottom: false,
        child: Row(
          children: [
            IconButton(
              icon: const Icon(Icons.arrow_back, color: Colors.white),
              onPressed: () => Navigator.of(context).pop(),
            ),
            Expanded(
              child: Text(
                chapter.title ?? '章节',
                style: const TextStyle(color: Colors.white, fontSize: 16),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            IconButton(
              icon: const Icon(Icons.download, color: Colors.white),
              onPressed: () {
                // TODO: 下载整章功能
                ScaffoldMessenger.of(context)
                    .showSnackBar(const SnackBar(content: Text('开始下载（未实现）')));
              },
            ),
            PopupMenuButton<String>(
              onSelected: (v) {},
              itemBuilder: (context) => [
                const PopupMenuItem(value: 'share', child: Text('分享')),
                const PopupMenuItem(value: 'report', child: Text('举报')),
              ],
              icon: const Icon(Icons.more_vert, color: Colors.white),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildBottomToolbar(ComicChapterModel chapter, int total) {
    final currentIndex = ref.watch(currentIndexProvider);
    final isVertical = ref.watch(isVerticalScrollProvider);
    return Container(
      color: Colors.black.withOpacity(0.6),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: SafeArea(
        top: false,
        bottom: true,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // progress slider
            Row(
              children: [
                Text('${currentIndex + 1}/$total',
                    style: const TextStyle(color: Colors.white)),
                Expanded(
                  child: Slider(
                    value: (currentIndex).toDouble(),
                    min: 0,
                    max: (total - 1).toDouble().clamp(0, double.infinity),
                    divisions: (total - 1) > 0 ? (total - 1) : null,
                    onChanged: (v) {
                      final target = v.toInt();
                      ref.read(currentIndexProvider.notifier).state = target;
                      // 跳页
                      if (isVertical) {
                        // no direct jump for ListView: scroll to index using item extent unknown => use Scrollable.ensureVisible with GlobalKey approach
                        // For simplicity here we'll use animateTo with an estimated position (you can improve by recording each item height)
                      } else {
                        _pageController?.animateToPage(target,
                            duration: const Duration(milliseconds: 300),
                            curve: Curves.easeInOut);
                      }
                    },
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.list, color: Colors.white),
                  onPressed: () {
                    // 从底部弹出目录列表
                    showModalBottomSheet(
                      context: context,
                      isScrollControlled: true,
                      backgroundColor: Colors.transparent,
                      builder: (context) => Container(
                        height: MediaQuery.of(context).size.height * 0.7,
                        decoration: const BoxDecoration(
                          color: Color(0xFF1A1A2E),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            topRight: Radius.circular(20),
                          ),
                        ),
                        child: Column(
                          children: [
                            // 顶部拖拽指示器
                            Container(
                              margin: const EdgeInsets.only(top: 12),
                              width: 40,
                              height: 4,
                              decoration: BoxDecoration(
                                color: Colors.grey[600],
                                borderRadius: BorderRadius.circular(2),
                              ),
                            ),
                            // 标题栏
                            Container(
                              padding: const EdgeInsets.all(16),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  const Text(
                                    '目录',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  IconButton(
                                    icon: const Icon(Icons.close,
                                        color: Colors.white),
                                    onPressed: () => Navigator.pop(context),
                                  ),
                                ],
                              ),
                            ),
                            const Divider(color: Color(0xFF3D2F5A), height: 1),
                            // 章节列表
                            Expanded(
                              child: Consumer(
                                builder: (context, ref, child) {
                                  final chapters =
                                      ref.watch(comicChaptersProvider);
                                  final currentChapterId =
                                      ref.watch(currentChapterIdProvider);

                                  return ListView.separated(
                                    padding:
                                        const EdgeInsets.symmetric(vertical: 8),
                                    itemCount: chapters.length,
                                    separatorBuilder: (_, __) => const Divider(
                                      color: Color(0xFF3D2F5A),
                                      height: 1,
                                      indent: 16,
                                      endIndent: 16,
                                    ),
                                    itemBuilder: (context, index) {
                                      final item = chapters[index];
                                      final isCurrentChapter =
                                          item.chapterId == currentChapterId;

                                      return Container(
                                        color: isCurrentChapter
                                            ? const Color(0xFF6C5CE7)
                                                .withOpacity(0.1)
                                            : Colors.transparent,
                                        child: ListTile(
                                          leading: Container(
                                            width: 32,
                                            height: 32,
                                            decoration: BoxDecoration(
                                              color: isCurrentChapter
                                                  ? const Color(0xFF6C5CE7)
                                                  : const Color(0xFF3D2F5A),
                                              borderRadius:
                                                  BorderRadius.circular(16),
                                            ),
                                            child: Center(
                                              child: Text(
                                                '${item.chapterNumber ?? (index + 1)}',
                                                style: TextStyle(
                                                  color: isCurrentChapter
                                                      ? Colors.white
                                                      : Colors.grey[400],
                                                  fontSize: 12,
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                            ),
                                          ),
                                          title: Text(
                                            item.chapterTitle ??
                                                '章节 ${item.chapterNumber ?? (index + 1)}',
                                            style: TextStyle(
                                              color: isCurrentChapter
                                                  ? const Color(0xFF6C5CE7)
                                                  : Colors.white,
                                              fontWeight: isCurrentChapter
                                                  ? FontWeight.bold
                                                  : FontWeight.normal,
                                            ),
                                          ),
                                          subtitle: Text(
                                            '第 ${item.chapterNumber ?? (index + 1)} 话',
                                            style: TextStyle(
                                              color: Colors.grey[400],
                                              fontSize: 12,
                                            ),
                                          ),
                                          trailing: isCurrentChapter
                                              ? const Icon(
                                                  Icons.play_arrow,
                                                  color: Color(0xFF6C5CE7),
                                                )
                                              : null,
                                          onTap: () {
                                            final id = item.chapterId;
                                            if (id != null) {
                                              // 重置当前页面索引到第一页
                                              ref
                                                  .read(currentIndexProvider
                                                      .notifier)
                                                  .state = 0;

                                              // 重置控制器位置
                                              if (_scrollController != null) {
                                                _scrollController!.jumpTo(0);
                                              }
                                              if (_pageController != null) {
                                                _pageController!.jumpToPage(0);
                                              }

                                              // 最后更新章节ID，触发数据重新加载
                                              ref
                                                  .read(currentChapterIdProvider
                                                      .notifier)
                                                  .state = id;
                                              Navigator.of(context).pop();
                                            }
                                          },
                                        ),
                                      );
                                    },
                                  );
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ],
            ),
            // actions row
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    IconButton(
                      icon: const Icon(Icons.brightness_2, color: Colors.white),
                      onPressed: () {
                        ref.read(nightModeProvider.notifier).state =
                            !ref.read(nightModeProvider);
                      },
                    ),
                    IconButton(
                      icon: const Icon(Icons.settings, color: Colors.white),
                      onPressed: () {
                        // TODO: 打开设置面板
                      },
                    ),
                  ],
                ),
                TextButton(
                  onPressed: () {
                    // 切换模式
                    ref.read(isVerticalScrollProvider.notifier).state =
                        !ref.read(isVerticalScrollProvider);
                  },
                  child: Text(
                    isVertical ? '条漫模式' : '翻页模式',
                    style: const TextStyle(color: Colors.white),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
